package com.hjwoo.app.views;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjwoo.app.R;
import com.hjwoo.app.adpter.CellInfoMationAdapter;
import com.hjwoo.app.baseviews.BaseAppCompatActivity;
import com.hjwoo.app.been.FailureResultObject;
import com.hjwoo.app.been.QueryDistrictObject;
import com.hjwoo.app.net.RequestListener;
import com.hjwoo.app.net.RequestMethod;
import com.hjwoo.app.net.RequestTag;
import com.hjwoo.app.ui.CenterAlertDialog;
import com.hjwoo.app.utils.LoanAccessTokenIdKeeper;
import com.hjwoo.app.utils.LoanToast;
import com.hjwoo.app.utils.Utils;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

/**
 * Created by zhaokaiwen on 2016/5/6 0006.
 * 小区信息 定位界面
 */
public class CellInformationActivity extends BaseAppCompatActivity implements RequestListener{

    //获取Activity实例
    public static CellInformationActivity instance;
    Gson gson = new Gson();
    EditText    autoTv;
    ImageButton cellinfomation_searchview;
    TextView    cellinfomation_lbs_tv;
    ListView    cellinfomation_lv, cellinfomation_history_lv;
    SharedPreferences sp;
    String city;
    LinkedList<QueryDistrictObject> ls;
    private String[] hisArrays;
    private AMapLocationClient mLocationClient = null;
    private TextView  item_history_tv;
    BaseAdapter baseAdapter = new BaseAdapter()
    {
        @Override
        public int getCount()
        {
            return hisArrays.length;
        }

        @Override
        public Object getItem(int i)
        {
            return i;
        }

        @Override
        public long getItemId(int i)
        {
            return i;
        }

        @Override
        public View getView(final int i, View view, final ViewGroup viewGroup)
        {
            view = View.inflate(CellInformationActivity.this, R.layout.item_history, null);
            item_history_tv = (TextView) view.findViewById(R.id.item_history_tv);

            item_history_tv.setText(hisArrays[i]);
            view.findViewById(R.id.select_listitem_image).setVisibility(View.VISIBLE);
            if (i == (hisArrays.length - 1))
            {
                item_history_tv.setGravity(Gravity.CENTER);
                view.findViewById(R.id.select_listitem_image).setVisibility(View.GONE);
            }
            view.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View view)
                {
                    if (hisArrays[i].equals("清除历史记录"))
                    {
                        autoTv.setText("");
                        new AlertDialog.Builder(CellInformationActivity.this)
                            .setIcon(android.R.drawable.ic_dialog_alert).setTitle("提示")
                            .setMessage("您是否要删除记录？")
                            .setPositiveButton("删除", new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    sp.edit().putString("history", "").commit();
                                    // 保存在sharedPreference中的字段名 要操作的AutoCompleteTextView
//                                            initAutoComplete("history", autoTv);
                                    initHistory("history", autoTv);
                                }
                            }).setNegativeButton("取消", null).show();
                    }
                    else
                    {
                        autoTv.setText(hisArrays[i]);
//                            将光标定义到最后面
                        autoTv.setSelection(autoTv.getText().length());
                    }
                }
            });
            return view;
        }
    };

    /**
     * 保存历史记录
     *
     * @param field
     * @param auto
     */
    private void initHistory(String field, EditText auto)
    {
        String longhistory = sp.getString("history", "");
        if (longhistory.length() == 0)
        {
            longhistory = "暂无记录";
        }

        if (!longhistory.equals("暂无记录"))
        {
            StringBuilder sb = new StringBuilder(longhistory);
            sb.append("清除历史记录,");
            longhistory = sb.toString();
        }
        hisArrays = longhistory.split(",");
        // 只保留最近的10条的记录
        if (hisArrays.length >= 10)
        {
            String[] newArrays = new String[10];
            System.arraycopy(hisArrays, 0, newArrays, 0, 10);
            hisArrays = Utils.concat(newArrays, new String[]{"清除历史记录"});
        }
        cellinfomation_history_lv.setAdapter(baseAdapter);
    }

    /**
     * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
     *
     * @param field 保存在sharedPreference中的字段名
     * @param auto  要操作的AutoCompleteTextView
     */
    private void saveHistory(String field, EditText auto)
    {

        String text = auto.getText().toString();

        String longhistory = sp.getString(field, "");
        if (!longhistory.contains(text + ","))
        {
            StringBuilder sb = new StringBuilder(longhistory);
            sb.insert(0, text + ",");
            sp.edit().putString("history", sb.toString()).commit();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        instance = CellInformationActivity.this;
        setContentView(R.layout.activity_cellinformation);
        Utils.initTitle("小区信息", this, true);
        city = getIntent().getStringExtra("city");
        sp = getSharedPreferences("network_url", 0);
        autoTv = (EditText) findViewById(R.id.cellinfomation_actv);
        cellinfomation_searchview = (ImageButton) findViewById(R.id.cellinfomation_searchview);
        cellinfomation_lbs_tv = (TextView) findViewById(R.id.cellinfomation_lbs_tv);
        cellinfomation_lv = (ListView) findViewById(R.id.cellinfomation_lv);
        cellinfomation_history_lv = (ListView) findViewById(R.id.cellinfomation_history_lv);

        autoTv.setFocusable(true);
        autoTv.requestFocus();

        // 保存在sharedPreference中的字段名 要操作的AutoCompleteTextView
//        initAutoComplete("history", autoTv);
        initHistory("history", autoTv);

        findViewById(R.id.cellinfomation_lbs_iv).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                initAmap();
            }
        });

        cellinfomation_searchview.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View view)
            {

                doQueryDistrict();
                // 这里可以设定：执行保存操作 将搜索记录保存到sp中去
                if (!autoTv.getText().toString().equals(""))
                {
                    saveHistory("history", autoTv);
                }
            }
        });
        cellinfomation_lbs_tv.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                autoTv.setText(cellinfomation_lbs_tv.getText().toString().trim());
                //                            将光标定义到最后面
                autoTv.setSelection(autoTv.getText().length());
            }
        });

        cellinfomation_lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
                Intent intent = new Intent(CellInformationActivity.this, HouseInformationActivity.class);
                intent.putExtra("city", city);
                intent.putExtra("nesidentialareaname", ls.get(i).getResidentialareaName());
                startActivity(intent);
            }
        });
        cellinfomation_history_lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
            {
            }
        });

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        //定位
        initAmap();
    }

    @Override
    protected void onRestart()
    {
        super.onRestart();
    }

    /**
     * 高德地图定位
     */
    private void initAmap()
    {
        cellinfomation_lbs_tv.setText("定位中...");
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(new AMapLocationListener()
        {

            @Override
            protected void finalize() throws Throwable
            {
                super.finalize();
            }

            @Override
            public void onLocationChanged(AMapLocation amapLocation)
            {
                if (amapLocation != null)
                {

                    switch (amapLocation.getErrorCode())
                    {
                    case AMapLocation.LOCATION_SUCCESS:
                        //定位成功回调信息，设置相关消息
                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        amapLocation.getLatitude();//获取纬度
                        amapLocation.getLongitude();//获取经度
                        amapLocation.getAccuracy();//获取精度信息
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(amapLocation.getTime());
                        df.format(date);//定位时间
                        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                        amapLocation.getCountry();//国家信息
                        amapLocation.getProvince();//省信息
                        amapLocation.getCity();//城市信息
                        amapLocation.getDistrict();//城区信息
                        amapLocation.getStreet();//街道信息
                        amapLocation.getStreetNum();//街道门牌号信息
                        amapLocation.getCityCode();//城市编码
                        amapLocation.getAdCode();//地区编码
                        Log.e("code返回码确认为0", "看具体显示文本信息是否获得");
                        Log.e("国家信息", amapLocation.getCountry());
                        Log.e("定位时间", df.format(date));
                        Log.e("地址", amapLocation.getAddress());
                        Log.e("城市信息", amapLocation.getCity());

                        //设置获取的位置
                        cellinfomation_lbs_tv.setText(amapLocation.getAddress());
                        break;
                    case AMapLocation.ERROR_CODE_FAILURE_LOCATION_PERMISSION:
                        //定位失败 没开权限
                        LoanToast.showToastLong("请开启定位权限", CellInformationActivity.this);
                        //设置获取的位置
                        cellinfomation_lbs_tv.setText("定位失败...");

                        new CenterAlertDialog(
                            CellInformationActivity.this, R.style.Theme_Popdialog, "打开定位开关",
                            "\b\b\b\b定位服务未开启，请进入[权限管理]>[隐私安全]中打开开关，允许黄金屋使用定位服务")
                        {
                            // 选择本地相册
                            @Override
                            public void doOK()
                            {
                                startActivity(getAppDetailSettingIntent(CellInformationActivity.this));
                                this.dismiss();
                            }

                        }.show();
                        break;
                    case AMapLocation.ERROR_CODE_FAILURE_CONNECTION:
                        LoanToast.showToastShort("网络连接异常", CellInformationActivity.this);
                        break;
                    }
                }
            }
        });
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）aa
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private Intent getAppDetailSettingIntent(Context context)
    {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9)
        {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        else if (Build.VERSION.SDK_INT <= 8)
        {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }

    /**
     * 寻值
     */

    private void doQueryDistrict()
    {
        RequestMethod.getMethod().doQueryDistrict(city, autoTv.getText().toString(), LoanAccessTokenIdKeeper.readAccessToken(CellInformationActivity.this).getAppSessionId(), CellInformationActivity.this, CellInformationActivity.this);
    }

    @Override
    public void requestSuccess(String tag, String message)
    {
        switch (tag)
        {
        case RequestTag.APPQUERYDISTRICT:
            //查询小区
            QueryDistrictObject queryDistrictObject = new QueryDistrictObject();
            Type listType = new TypeToken<LinkedList<QueryDistrictObject>>()
            {
            }.getType();
            ls = gson.fromJson(message, listType);

            CellInfoMationAdapter CellInfoMationAdapter = new CellInfoMationAdapter(CellInformationActivity.this, ls);
            cellinfomation_lv.setAdapter(CellInfoMationAdapter);
            //     将搜索结果设置为显示
            findViewById(R.id.cellinfomation_show_ll).setVisibility(View.VISIBLE);
            break;
        }
    }

    @Override
    public void requestError(String message)
    {
        //     将搜索结果设置为隐藏
        findViewById(R.id.cellinfomation_show_ll).setVisibility(View.GONE);
        FailureResultObject failureResultObject = new FailureResultObject();
        failureResultObject = gson.fromJson(message, FailureResultObject.class);
        LoanToast.showToastShort(failureResultObject.getErrorMessage(), CellInformationActivity.this);
    }
}
